package service.impl;


import domain.Comment;
import domain.User;
import domain.UserRole;
import exceptions.GeneralServiceException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import service.IUserService;
import service.MailService;

/**
 *
 * @author yuyok
 */
@Stateless
@LocalBean
public class UserServiceImpl extends GenericServiceImpl<User> implements IUserService {

    @PersistenceContext(unitName = "onlinetvPU")
    private EntityManager em;
    
    public UserServiceImpl() {
        super(User.class);
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    @Override
    public User getUserByLoginAndPassword(String login, String password) throws IllegalArgumentException {

        if (login == null || password == null) {
            throw new IllegalArgumentException("Login and password cannot be null while getting User by these fields");
        }

        Query query = getEntityManager().createNamedQuery("getUserByLoginAndPassword");

        query.setParameter("login", login);
        try {
            query.setParameter("password", md5(password));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            return (User) query.getSingleResult();
        } catch (NoResultException noRes) {
            return null;
        }
    }

    @Override
    public List<User> getUsersByRole(UserRole role) {
        if (role == null) {
            throw new IllegalArgumentException("Role cannot be null while getting by this field");
        }

        Query query = getEntityManager().createNamedQuery("getUsersByRole");
        query.setParameter("role", role.toString());

        return query.getResultList();
    }

    @Override //TODO: md5
    public User register(User user) throws IllegalArgumentException, GeneralServiceException {
        MailService mail = new MailService();
        String subject = "welcome to onlineTV";
        String text = "Hope you enjoy our site";
        mail.sendMail(user.getEmail(), subject, text);
        
        user.setIsEnable(true);
        try {
            user.setPassword(md5(user.getPassword()));
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
        return save(user);
    }

    @Override
    public List<Comment> getCommentsByUserLogin(String login) throws IllegalArgumentException {
        if (login == null) {
            throw new IllegalArgumentException("Login cannot be null while getting by this field");
        }

        Query query = getEntityManager().createNamedQuery("getCommentsByUserLogin");
        query.setParameter("login", login);

        return query.getResultList();
    }

    @Override
    public void addNewSupplier(User user) throws IllegalArgumentException {
        user.setRole("SUPPLIER");
        try {
            save(user);
        } catch (GeneralServiceException ex) {
            Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

//    @Override
//    protected void beforeEntityDelete(User entity) {
//        throw new UnsupportedOperationException("Not supported yet.");
//    }

    public String hex(byte[] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; ++i) {
            sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3));
        }
        return sb.toString();
    }

    public String md5(String password) throws UnsupportedEncodingException {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return hex(md.digest(password.getBytes("CP1252")));
        } catch (NoSuchAlgorithmException e) {
        } catch (UnsupportedEncodingException e) {
        }
        return null;
    }

    @Override
    public void confirmUser(String login) {
        if (login == null) {
            throw new IllegalArgumentException("Login cannot be null while getting by this field");
        }
        
        User user = getUserByLogin(login);
        user.setIsEnable(true);
        try {
            save(user);
        } catch (GeneralServiceException ex) {
            Logger.getLogger(UserServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public User getUserByLogin(String login) throws IllegalArgumentException {

        if (login == null) {
            throw new IllegalArgumentException("Login cannot be null while getting User by these fields");
        }

        Query query = getEntityManager().createNamedQuery("getUserByLogin");

        query.setParameter("login", login);

        try {
            return (User) query.getSingleResult();
        } catch (NoResultException noRes) {
            return null;
        }
    }

    @Override
    public List<User> getAllUsers() {
        Query query = getEntityManager().createNamedQuery("getAllUsers");
        
        return query.getResultList();
    }
}
